package com.zzyl.intercept;

import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class UserHandlerException implements HandlerInterceptor {

    //请求之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("authorization");
        //token为null 报错
        if(Objects.isNull(token)){
            throw new RuntimeException();
        }
        //claims解析不出来会自动报错->token出问题
        Claims claims = JwtUtil.parseJWT("$2a$10$PVtHnkj86mJgf6li/yron.LRx/cQAlaiZkBJ9BeogCNTryXJRT1YC",token);
        //claims的值是null 也应当报错
        if(Objects.isNull(claims.get("id"))){
            throw new RuntimeException();
        }
        Long userId=Long.valueOf((Integer)claims.get("id"));
        UserThreadLocal.set(userId);

        return true;//放行
    }

    //请求之后拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();//销毁
    }
}
